package org.example.flea_market_mvc.controller;

import org.example.flea_market_mvc.entity.ShoppingCarts;
import org.example.flea_market_mvc.param.ShoppingCartParam;
import org.example.flea_market_mvc.service.shoppingcarts.ShoppingCartsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.List;

@RestController
@RequestMapping("/api/shopping-carts")
@Validated
public class ShoppingCartsController {

    @Autowired
    private ShoppingCartsService shoppingCartsService;

    @PostMapping
    public ApiResponse<String> addToCart(@Valid @RequestBody ShoppingCartParam shoppingCartParam) {
        int result = shoppingCartsService.insert(shoppingCartParam);
        return result > 0 ? ApiResponse.success("添加购物车成功") : ApiResponse.error(400, "添加购物车失败");
    }

    @DeleteMapping("/{id}")
    public ApiResponse<String> removeFromCart(@PathVariable Integer id) {
        int result = shoppingCartsService.deleteById(id);
        return result > 0 ? ApiResponse.success("删除购物车项成功") : ApiResponse.notFound("购物车项不存在");
    }

    @PutMapping
    public ApiResponse<String> updateCart(@Valid @RequestBody ShoppingCartParam shoppingCartParam) {
        int result = shoppingCartsService.update(shoppingCartParam);
        return result > 0 ? ApiResponse.success("更新购物车成功") : ApiResponse.notFound("购物车项不存在");
    }
    @PutMapping("/updateCartQuantity/{id}/{data}")
    public ApiResponse<String> updateCartQuantity(@PathVariable Integer id,@PathVariable Integer data) {
        int result = shoppingCartsService.updateCartQuantity(id,data);
        return result > 0 ? ApiResponse.success("更新购物车成功") : ApiResponse.notFound("购物车项不存在");
    }

    @GetMapping("/{id}")
    public ApiResponse<ShoppingCarts> getCartItem(@PathVariable Integer id) {
        ShoppingCarts cartItem = shoppingCartsService.selectById(id);
        return cartItem != null ? ApiResponse.success(cartItem) : ApiResponse.notFound("购物车项不存在");
    }

    @GetMapping
    public ApiResponse<List<ShoppingCarts>> getAllCartItems() {
        List<ShoppingCarts> cartItems = shoppingCartsService.selectAll();
        return ApiResponse.success(cartItems);
    }

    @GetMapping("/user/{userId}")
    public ApiResponse<List<ShoppingCarts>> getCartItemsByUser(@PathVariable Integer userId) {
        try{
            List<ShoppingCarts> cartItems = shoppingCartsService.selectByUserId(userId);
            return ApiResponse.success(cartItems);
        } catch (Exception e){
            e.printStackTrace();
            return ApiResponse.error(500, e.getMessage());
        }


    }

    // 游客（未登录）添加购物车，数据存Session
    @PostMapping("/session/add")
    public ApiResponse<String> addToSessionCart(@Valid @RequestBody ShoppingCartParam shoppingCartParam, HttpSession session) {
        List<ShoppingCartParam> cart = (List<ShoppingCartParam>) session.getAttribute("cart");
        if (cart == null) cart = new java.util.ArrayList<>();
        cart.add(shoppingCartParam);
        session.setAttribute("cart", cart);
        return ApiResponse.success("已加入临时购物车");
    }

    // 游客（未登录）查看Session购物车
    @GetMapping("/session/list")
    public ApiResponse<List<ShoppingCartParam>> getSessionCart(HttpSession session) {
        List<ShoppingCartParam> cart = (List<ShoppingCartParam>) session.getAttribute("cart");
        if (cart == null) cart = new java.util.ArrayList<>();
        return ApiResponse.success(cart);
    }

    // 登录后合并Session购物车到数据库
    @PostMapping("/session/merge")
    public ApiResponse<String> mergeSessionCartToDb(@RequestParam Integer userId, HttpSession session) {
        List<ShoppingCartParam> cart = (List<ShoppingCartParam>) session.getAttribute("cart");
        if (cart != null && !cart.isEmpty()) {
            for (ShoppingCartParam item : cart) {
                item.setUserId(userId);
                shoppingCartsService.insert(item);
            }
            session.removeAttribute("cart");
        }
        return ApiResponse.success("购物车已合并");
    }
}